using System;
using System.Windows.Forms;
using SDM3Server;
using System.ComponentModel;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public static SDM3Server.SDM3 SDM = new SDM3();
        public static string DimmerID = "0D.95.48";
        private delegate void AnonymousDelegate();

        public Form1()
        {
            InitializeComponent();
            startPLC();
        }

        private void startPLC()
        {
            button1.Enabled = false;
            button2.Enabled = false;
            checkBox1.Enabled = false;
            bwConnectPLC.RunWorkerAsync();
            this.Text = "McHAM: v1.0 beta";
            this.statusBar.Text = "Connecting...";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }
        private void button1_Click(object sender, EventArgs e)
        {
            TurnOn();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            TurnOff();
        }
       
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            closeSDM();
        }

        private void bwConnectPLC_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            BackgroundWorker bwAsync = (BackgroundWorker)sender;
            addSDMEvents();
            while(true)
            {
                if (bwAsync.CancellationPending)
                {
                    e.Cancel = true;
                    toolStripStatusLabel1.Text = "Error Connecting to PLC.  Ensure usb cable is connected";
                    return;
                }
            }
        }


        private void SDM_OnText(String text)
        {
           
        
            //DM=active,1.01.138.308,8/4/2008 4:20:18 PM,unresponsive,,0.0,xdevices=True
            if (text.Contains("DM=active"))
            {
                string[] temp = text.Split(',');
                switch (temp[3])
                {
                    case "responded":
                        AnonymousDelegate del = delegate() { EnableButtons(); };
                        button1.BeginInvoke(del);
                        break;
                    case "unresponsive":
                        bwConnectPLC.CancelAsync();
                        break;
                    default:
                        break;
                }
                return;
            }

            if (text.Contains("setOnLevelText="))
            {
                AnonymousDelegate del;
                string[] temp = text.Split(',');

                switch (temp[1])
                {
                    case "ON":
                        del = delegate() { checkBox1.CheckState = CheckState.Checked; };
                        checkBox1.BeginInvoke(del);
                        break;
                    case "OFF":
                        del = delegate() { checkBox1.CheckState = CheckState.Unchecked; };
                        checkBox1.BeginInvoke(del);
                        break;
                    default:
                        break;
                }
                return;
            }
        }

        void bwGetLightStatus_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                    string checklevel = SDM.GetOnLevelText(DimmerID);
                    AnonymousDelegate del;
                    if (checklevel.Contains("%"))
                    {
                        del = delegate() { checkBox1.CheckState = CheckState.Checked; button1.Enabled = false; button2.Enabled = true; };
                        checkBox1.BeginInvoke(del);
                    }
                    else
                    {
                        switch (checklevel)
                        {
                            case "ON":
                                del = delegate() { checkBox1.CheckState = CheckState.Checked; button1.Enabled = false; button2.Enabled = true; };
                                checkBox1.BeginInvoke(del);
                                break;
                            case "OFF":
                                del = delegate() { checkBox1.CheckState = CheckState.Unchecked; button1.Enabled = true; button2.Enabled = false; };
                                checkBox1.BeginInvoke(del);
                                break;
                            default:
                                break;

                        }
                    }
                   

                    System.Threading.Thread.Sleep(1000);
                }
                catch (Exception er)
                {
                }
            }
        }

        private void EnableButtons()
        {
            button1.Enabled = true;
            button2.Enabled = true;
            checkBox1.Enabled = true;
        }

        private void SDM_OnConnectedAndReady()
        {
            toolStripStatusLabel1.Text = "Ready";
            BackgroundWorker bwCheckLights = new BackgroundWorker();
            bwCheckLights.DoWork += new DoWorkEventHandler(bwGetLightStatus_DoWork);
            bwCheckLights.RunWorkerAsync();
            DateTime tod = DateTime.Now.AddMinutes(1);
            string timertest = "<Timers><ItemCount>1</ItemCount><Timer><TID Name=\"PLCTimer1\">PLCTimer1</TID><DeviceList><Device DID=\"1\" Address=\"" + SDM.GetMyID() + "\" HouseCode=\"\" UnitCode=\"\" OnLevel=\"On\" DeviceName=\"Dimmer\">Dimmer</Device></DeviceList><TOD>" + tod.ToString("HHmm") +"</TOD><PlusMinusMin>0</PlusMinusMin><DOW>SuMTuWThFSa</DOW><Security>NOSEC</Security></Timer></Timers>";
            SDM.SendText(timertest);
            
        }


        

        internal void TurnOn()
        {
            SDM.SetOnLevelText(DimmerID, "100%");

        }
        internal void TurnOff()
        {
            SDM.SetOnLevelText(DimmerID, "0%");
        }
        
        private void addSDMEvents()
        {
            SDM.OnText += new ISDM3Events_OnTextEventHandler(SDM_OnText);
            SDM.OnConnectedAndReady += new ISDM3Events_OnConnectedAndReadyEventHandler(SDM_OnConnectedAndReady);
        }
        internal void closeSDM()
        {
            KillSDMProcess();
            SDM = null;
        }

        void bwCheckDevice1Status_DoWork(object sender, DoWorkEventArgs e)
        {
            
        }

        private void KillSDMProcess()
        {
            System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("SDM3");
            foreach (System.Diagnostics.Process p in process)
            {
                if (p != null)
                {
                    p.Kill();
                }
            }
        }

        private void getLinksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SDM.SendText("getLinks");
        }
    }
}